using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;

[AddComponentMenu ( "Chromatic2D/C2DSpline" )]
public class C2DSpline : MonoBehaviour 
{
	public const float CONTROL_POINT_SIZE = 20.0f;
	
	//[SerializeField]
	public List<C2DControlPoint> m_ControlPoints = new List<C2DControlPoint>();
	
	#if UNITY_EDITOR
	
	/// <summary>
	/// Creates an empty spline.
	/// </summary>
	[MenuItem("GameObject/Create Other/C2DSpline")]
	public static void CreateC2DSpline()
	{
		GameObject go = new GameObject("New Spline");
		go.AddComponent( typeof(C2DSpline) );
	}
	
	#endif
	
	/// <summary>
	/// Adds a node to the list
	/// </summary>
	public void AddNode( Vector3 Position )
	{
		C2DControlPoint point = new C2DControlPoint();
		point.m_Position = Position;
		
		if( m_ControlPoints.Count == 0 )	
		{
			transform.position = Position;
		}
		
		m_ControlPoints.Add( point );
	}
	
	/// <summary>
	/// Pick a control point from a 3d point in a space
	/// </summary>
	public C2DControlPoint GetPointNear( Vector3 pos )
	{
		for( int n= 0 ; n < m_ControlPoints.Count ; n++ )
		{
			if( Vector3.Distance( m_ControlPoints[n].m_Position, pos) < CONTROL_POINT_SIZE )
			{
				return m_ControlPoints[n];
			}
		}
		
		return null;
	}
	
	/// <summary>
	/// Selects a point in the list
	/// </summary>
	public C2DControlPoint SelectPoint( Vector3 pos )
	{
		C2DControlPoint point =  GetPointNear( pos );
		
		if( point != null )
		{
			transform.position = point.m_Position;
		}
		else
		{
			transform.position = Vector2.zero;
		}
		
		return point;
		
	}

	
	// Use this for initialization
	void Start () 
	{
	
	}
	
	// Update is called once per frame
	void Update () 
	{
	
	}
}
